import React, { useRef, useState } from "react";
import SDTable from "./SDTable";
import { DeleteTwoTone, EditTwoTone } from "@ant-design/icons";
import DEFAULT_API from "src/api";
import { LoadingOutlined ,PlusOutlined} from '@ant-design/icons';
import {
  Button,
  Form,
  Modal,
  Input,
  Col,
  Row,
  Select,
  InputNumber,
  message,
  Upload,
} from "antd";
import useReducer from "src/hooks/useReducer";
import moment from "moment";
const layout = {
  labelCol: { span: 8 },
  wrapperCol: { span: 16 },
};
const roleOptions = [
  //商品类型
  { label: "电子产品", value: "电子产品" },
  { label: "食品", value: "食品" },
  { label: "服装", value: "服装" },
  { label: "日用品", value: "日用品" },
  { label: "其他", value: "其他" },
];
const roleObj = {
  甲管理员: 1,
  乙管理员: 2,
  普通用户: 3,
};

const DataManage = () => {
  const formRef = useRef(null);
  const actionRef = useRef(null);
  const [form] = Form.useForm();

  const [sate, dispatch] = useReducer({
    visible: false, // 抽屉弹窗
    editId: "", // 编辑id
    title: "", // 抽屉标题
  });
  const { visible, editId, title } = sate;

  const columns = [
    {
      title: "序号",
      dataIndex: "index",
      width: 80,
      hideInSearch: true,
      render: (text, record, index) => `${index + 1}`,
    },
    {
      title: "商品名称",
      dataIndex: "name",
      with: 200,
      exact: true,
    },
    // 收件人  订单重量（kg） 快递种类  订单时间  订单状态  操作
    {
      title: "商品描述",
      dataIndex: "description",
      with: 200,
      exact: true,
      hideInSearch: true,
    },
    {
      title: "商品价格",
      dataIndex: "price",
      with: 200,
      exact: true,
      hideInSearch: true,
    },

    {
      title: "商品类型",
      dataIndex: "type",
      with: 200,
      exact: true,
    },
    {
      title: "商品品牌",
      dataIndex: "brand",
      with: 200,
      exact: true,
      hideInSearch: true,
    },
    {
      title: "更新时间",
      dataIndex: "updateTime",
      with: 200,
      exact: true,
      hideInSearch: true,
    },
    {
      title: "操作",
      value: "option",
      width: 100,
      fixed: "right",
      hideInSearch: true,
      render: (text, record) => {
        return (
          <>
            <EditTwoTone
              style={{ fontSize: "20px", marginRight: 10 }}
              onClick={() => handleEdit(record)}
            />
            <DeleteTwoTone
              //设置大点
              style={{ fontSize: "20px" }}
              twoToneColor="red"
              onClick={() => handleDelete(record)}
            />
          </>
        );
      },
    },
  ];

  // 删除
  const handleDelete = (record) => {
    Modal.confirm({
      title: "提示",
      content: "确定删除该用户吗？",
      okText: "确定",
      cancelText: "取消",
      onOk: async () => {
        const res = await DEFAULT_API.delete({ id: record.id });
        if (res.success) {
          message.success(res.message || "操作成功");
          actionRef.current.reload();
        } else {
          message.error(res.message || "操作失败");
        }
      },
    });
  };

  // 新增
  const handleAdd = () => {
    form.resetFields();
    dispatch({
      visible: true,
      editId: "",
      title: "新增",
    });
  };

  // 编辑
  const handleEdit = (record) => {
    form.setFieldsValue({
      ...record,
      userRoleId: roleObj[record.roleName],
    });
    dispatch({
      visible: true,
      editId: record.id,
      title: "编辑",
    });
  };

  //保存
  const save = () => {
    form.validateFields().then((values) => {
      const params = {
        ...values,
      };
      editId && (params.id = editId);

      // 如果是新增， 那么userCreate 就是设置当前时间
      if (!editId) {
        params.userCreate = moment().format("YYYY-MM-DD HH:mm:ss");
      }

      const remote = editId ? DEFAULT_API.edit : DEFAULT_API.add;

      remote(params).then((res) => {
        if (res.success) {
          dispatch({ visible: false });
          actionRef.current.reload();
          message.success("操作成功");
        } else {
          message.error(res.message || "操作失败");
        }
      });
    });
  };

///图片上传

  const [loading, setLoading] = useState(false);
  const [imageUrl, setImageUrl] = useState();
  const getBase64 = (img, callback) => {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result));
    reader.readAsDataURL(img);
  };
  const beforeUpload = (file) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
      message.error('You can only upload JPG/PNG file!');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error('Image must smaller than 2MB!');
    }
    return isJpgOrPng && isLt2M;
  };
  const uploadButton = (
    <button
      style={{
        border: 0,
        background: 'none',
      }}
      type="button"
    >
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div
        style={{
          marginTop: 8,
        }}
      >
        Upload
      </div>
    </button>
  );
 
  const handleChange = (info) => {
    if (info.file.status === 'uploading') {
      setLoading(true);
      const formData = new FormData();
      formData.append('file', info.file.originFileObj);
      formData.append('id', editId); // 传递 id 参数
      DEFAULT_API.upload(formData).then((res) => {
        if (res.success) {
          message.success('上传成功');
          setLoading(false);
          setImageUrl(res.message);
        } else {
          message.error(res.message || '上传失败');
        }
      });
      return;
    }
    if (info.file.status === 'done') {
      // Get this url from response in real world.
      getBase64(info.file.originFileObj, (url) => {
        setLoading(false);
        setImageUrl(url);
      });
    }
  };
  return (
    <>
      <SDTable
        formRef={formRef}
        actionRef={actionRef}
        requestApi={DEFAULT_API.page}
        columns={columns}
        options={false}
        toolBarRender={() => [
          <Button type="primary" key="1" onClick={handleAdd}>
            新增商品信息
          </Button>,
        ]}
      />
      <Modal
        visible={visible}
        title={`${title}商品信息`}
        width={900}
        onCancel={() => dispatch({ visible: false })}
        footer={[
          <Button key="back" onClick={() => dispatch({ visible: false })}>
            取消
          </Button>,
          <Button key="submit" type="primary" onClick={save}>
            确定
          </Button>,
        ]}
      >
        <Form form={form} {...layout}>
          <Row gutter={24}>
            <Col span={12}>
              <Form.Item
                name="name"
                label="商品名称"
                rules={[
                  {
                    required: true,
                    message: "商品名称",
                  },
                ]}
              >
                <Input />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="description"
                label="商品描述"
                rules={[
                  {
                    required: true,
                    message: "商品描述",
                  },
                ]}
              >
                <Input />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={24}>
            <Col span={12}>
              <Form.Item
                name="price"
                label="商品价格"
                rules={[
                  {
                    required: true,
                    message: "商品价格",
                  },
                ]}
              >
                <Input allowClear />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="type"
                label="商品类型"
                rules={[
                  {
                    required: true,
                    message: "商品类型",
                  },
                ]}
              >
                <Select options={roleOptions} allowClear />
              </Form.Item>
            </Col>
          </Row>
          <Col span={12}>
            <Form.Item
              name="brand"
              label="商品品牌"
              rules={[
                {
                  required: true,
                  message: "商品品牌",
                },
              ]}
            >
              <Input allowClear />
            </Form.Item>
          </Col>
          
          {/* <Col span={12}>
            <Form.Item
              name="updateTime"
              label="图片上传"
              rules={[
                {
                  required: true,
                  message: "图片上传",
                },
              ]}
            >
              <Upload
                name="avatar"
                listType="picture-card"
                className="avatar-uploader"
                showUploadList={false}
                beforeUpload={beforeUpload}
                onChange={handleChange}
              >
                {imageUrl ? (
                  <img
                    src={imageUrl}
                    alt="avatar"
                    style={{
                      width: "100%",
                    }}
                  />
                ) : (
                  uploadButton
                )}
              </Upload>
            </Form.Item>
          </Col> */}
        </Form>
      </Modal>
    </>
  );
};
export default DataManage;
